package net.helpfulwebservices.cogitologopedia;

import net.helpfulwebservices.cogitologopedia.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;


public class Activity_game extends Activity {
	
	private int x;
	private int y;
    final Handler mHandler = new Handler();
    
	
	/**
	 * @return the x
	 */
	public int getX() {
		return x;
	}

	/**
	 * @param x the x to set
	 */
	public void setX(int x) {
		this.x = x;
	}

	/**
	 * @return the y
	 */
	public int getY() {
		return y;
	}

	/**
	 * @return the y
	 */
	public GridView getGridview() {
		return this.setMatrix(this.getX(), this.getY());
	}

	
	/**
	 * @param y the y to set
	 */
	public void setY(int y) {
		this.y = y;
	}

	public Activity_game(){
		
	}
	
	private GridView setMatrix(int x, int y){
		ImageAdapter imageAdapter = new ImageAdapter(this,x,y);
		Log.w(Activity_game.class.getName(), "imageAdapter.getCount(): " + imageAdapter.getCount());

		
		GridView gridview = (GridView) findViewById(R.id.gridMatrix);
        gridview.setNumColumns(x);
        gridview.setAdapter(imageAdapter);
        return gridview;
        
        
	}

	
	private void UpdateCounter(int counter){
		TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
		txtCounter.setText("Mosse: " + counter);
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        
        
        //leggo i parametri per la matrice
        Bundle extras = getIntent().getExtras();
        this.setX(extras.getInt("X"));
        this.setY(extras.getInt("Y"));
        
        startLongRunningOperation();
        
        Log.v(Activity_game.class.getName(),"Activity_game:onCreate()");
        Log.v(Activity_game.class.getName(),"[x=" + this.getX() + ",y="+this.getY()+"]");
        GridView gridview  = this.setMatrix(this.getX(), this.getY());
        gridview.setOnItemClickListener((new OnItemClickListener() 
        {

        	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
            {
        		
                Log.v(Activity_game.class.getName(),"onItemClick():"+arg0.toString());
        		ImageAdapter imageAdapter = (ImageAdapter) arg0.getAdapter();
        		
        		
        		if ((imageAdapter.CheckMove(arg2)==true)){
        			imageAdapter.AppliesMovie(arg2);
        			imageAdapter.CheckNextMove();
        		}
        		if (imageAdapter.isGameOver()==true){
        			AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
        			builder.setCancelable(true);

        			builder.setIcon(R.drawable.info);
        			builder.setTitle("Game over");
        			builder.setMessage("Complimenti hai vinti!");
        			builder.setInverseBackgroundForced(true);
        			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dialog, int which) {
        					finish();    		
        				}
        			});
        			AlertDialog alert = builder.create();
        			alert.show();
        			

        		}
        		
        		/*
        		
        		 
        		if ((imageAdapter.CheckMove(arg2)==true)){
        			imageAdapter.AppliesMovie(arg2);
        			imageAdapter.CheckMove();
        		}
/*
        		 * if ((imageAdapter.tryMove(arg2)==true)&&(imageAdapter.CheckGameOver()==false)){
        			imageAdapter.Applies(arg2);
        			imageAdapter.CheckMove();
        		}else{
        			
        		}
*/        		
        		
        		imageAdapter.notifyDataSetChanged();
        		//aggiorno l'interfaccia grafica con il contatore delle mosse
        		UpdateCounter(imageAdapter.getCountSingleGame());
            }
        }
        ));
        
		//aggiorno l'interfaccia grafica con il contatore delle mosse
		UpdateCounter(0);
	}
	

    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateResultsInUi();
        }
    };
    
	protected void startLongRunningOperation() {
	    Thread t = new Thread() {
	    	public void run() {
	    		while(true){
	    			try {
		    			mHandler.post(mUpdateResults);
						Thread.sleep(1500);
					} catch (InterruptedException e) {
				        Log.e(Activity_game.class.getName(),e.getMessage());
					}
	    		}
	    	}
	    };
	    t.start();
	}

	private void updateResultsInUi() {
		
		GridView gridview = (GridView) findViewById(R.id.gridMatrix);
		
		ImageAdapter imageAdapter = (ImageAdapter) gridview.getAdapter();
		Log.v(Activity_game.class.getName(),"Start: updateResultsInUi()");
		Log.v(Activity_game.class.getName()," ==> size vettore mosse: " + imageAdapter.getMoves().size());

		if (imageAdapter.getMoves().size()==2){
			Log.v(Activity_game.class.getName()," ==> inizio la pulizia del vettore mosse !");
			imageAdapter.UpdateStatusArrayCards();
			imageAdapter.notifyDataSetChanged();
			imageAdapter.getMoves().clear();
		}
	}	
}
